<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择分类 -->
      <el-row class="sel_cate">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="cascaderChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, id) in scope.row.attr_vals"
                  :key="id"
                  closable
                  @close="deleteAttr(scope.row, id)"
                >
                  {{ item }}
                </el-tag>

                <!-- 文本框和按钮区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model="scope.row.inputValue"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数信息"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
             <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, id) in scope.row.attr_vals"
                  :key="id"
                  closable
                  @close="deleteAttr(scope.row, id)"
                >
                  {{ item }}
                </el-tag>

                <!-- 文本框和按钮区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model="scope.row.inputValue"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性信息"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="doaa(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + getTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="getTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑' + getTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="getTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      selectedKeys: [],
      // 商品分类列表
      cateList: [],
      // 级联选择器属性
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      activeName: 'many',
      // 动态参数表格数据
      manyTableData: [],
      // 静态属性表格数据
      onlyTableData: [],
      // 表单对象
      addForm: {
        attr_name: ''
      },
      // 表单规则对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数信息', trigger: 'blur' }
        ]
      },
      addDialogVisible: false,
      // 显示编辑对话框
      editDialogVisible: false,
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数信息', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  // 计算属性
  computed: {
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取分类ID
    getCateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 标题
    getTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // 获取商品分类信息
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类信息失败！')
      }

      this.cateList = res.data
    },
    // 级联选择器改变事件
    cascaderChange () {
      this.getParamsData()
    },
    // 获取参数数据
    async getParamsData () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }

      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) this.$message.error('获取参数列表失败！')

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框显示和隐藏
        item.inputVisible = false
        // 文本框中的输入值
        item.inputValue = ''
      })

      console.log(res.data)

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // tab点击事件处理函数
    handleTabClick () {
      this.getParamsData()
    },
    // 对话框关闭事件
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    addParams () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.post(
          `categories/${this.getCateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.getParamsData()
        this.addDialogVisible = false
        this.$message.success('添加参数成功！')
      })
    },
    // 展示编辑对话框
    async showEditDialog (arr_id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(
        `categories/${this.getCateId}/attributes/${arr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) { return this.$message.error('获取参数信息失败！') }
      this.editForm.attr_name = res.data.attr_name
      this.editForm.attr_id = arr_id
    },
    // 编辑对话框关闭
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑参数
    editParams () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          `categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败！')
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success('修改成功！')
      })
    },
    // 删除
    async deleteParams (attr_id) {
      const info = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (info !== 'confirm') return this.$message.warning('取消了删除操作')

      const { data: res } = await this.$http.delete(
        `categories/${this.getCateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败！')
      this.getParamsData()
      this.$message.success('删除成功！')
    },
    // 文本框失去焦点或者按下 Enter 键时触发
    handleInputConfirm (row) {
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim())
        this.saveAttrs(row)
      }

      row.inputVisible = false
      row.inputValue = ''
    },
    // 保存参数
    async saveAttrs (row) {
      const { data: res } = await this.$http.put(`categories/${this.getCateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })

      if (res.meta.status !== 200) return this.$message.error('修改参数失败！')

      this.$message.success('修改参数成功！')
    },
    // 按下按钮时触发
    showInput (row) {
      row.inputVisible = true

      // $nextTick 的作用，就是当页面中的元素重新渲染之后，才会执行指定回调函数中的方法
      // 在此方法中，当按钮被点击之后，文本框还没有被渲染，所有无法设置文本框的焦点，所以用$nextTick方法，当元素被渲染之后才执行内部代码
      this.$nextTick(_ => {
        // 让文本框自动获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 参数参数可选项
    deleteAttr (row, id) {
      row.attr_vals.splice(id, 1)
      this.saveAttrs(row)
    }
  }
}
</script>

<style lang="less" scoped>
.sel_cate {
  margin: 20px 0;
}
.input-new-tag {
    width: 120px;
}
.el-tag {
    margin-right: 15px;
}
</style>
